import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
    {
      path: "/layout",
      component: () => import("../views/layout.vue"),
      children:[
        {
          path: "/index",
          component: () => import("../views/index.vue"),
        },
        {
          path: "/menu",
          component: () => import("../views/menu.vue"),
        },
        {
          path: "/role",
          component: () => import("../views/role.vue"),
        },
        {
          path: "/user",
          component: () => import("../views/user.vue"),
        },
        
      ]
    },
    {
      path: "/login",
      component: () => import("../views/login.vue"),
    }
]

const router = new VueRouter({
  routes
})

router.beforeEach(function(to,from,next){
  //设置白名单
  const no_login_list = ['/login'] //就是不需要校验token的名单
  if(no_login_list.indexOf(to.path) === -1){//不在白名单，需要登录校验
    //获取localstorage当中的token，校验是否存在
    var tokenString = localStorage.getItem("login_data")||'{}' //获取的字符串格式的用户信息
    var token = JSON.parse(tokenString).token //使用json进行格式转化 string --> object
    if(token){
      next()
    }else{
      next("/login")
    }
  }else{
    next()
  }
})

export default router
